package com.hd.trans.files.repository;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;

import androidx.annotation.RequiresApi;

import com.hd.trans.R;
import com.hd.trans.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Author: yangtianwen
 * Time: 2021/12/10
 * Des: 文件保存
 */
public class StoreRepository {

    public static final String TAG = "StoreRepository";

    public void storeAudio(Context context, String path) {
        store(context, path);
    }

    /**
     * 保存
     */
    private void store(Context context, String filePath) {
        String destFileName = FileUtils.getAudioPath();
        String destPath = moveFile(filePath, destFileName);
        if (destPath != null) {
            boolean store = storeMusicInfo(context, destPath, null);
            if (!store) {
                Log.e(TAG, TAG + "文件保存不成功");
            }
        }
    }

    /**
     * 移动文件
     *
     * @param srcFilePath 源文件完整路径
     * @param destDirName 目的目录完整路径
     * @return 移动成功返回移动后的路劲失败返回null
     */
    public static String moveFile(String srcFilePath, String destDirName) {

        File srcFile = new File(srcFilePath);
        if (!srcFile.exists() || !srcFile.isFile())
            return null;

        File destDir = new File(destDirName);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        String destFilePath = destDirName + File.separator
                + srcFile.getName();
        String destFileName = keepFileNameUnique(destFilePath);
        boolean result = srcFile.renameTo(new File(destDirName + File.separator
                + destFileName));
        return result ? destDirName + File.separator + destFileName : null;
    }

    /**
     * 保证文件名不重复
     */
    public static String keepFileNameUnique(String filePath) {
        int i = 1;
        File file = new File(filePath);
        String fileName = new File(filePath).getName();
        String destDirName = file.getParent();
        String name = fileName.substring(0, fileName.lastIndexOf("."));
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        while (file.exists()) {
            file = new File(destDirName + File.separator + name + "(" + i + ")" + suffix);
            i++;
        }
        return file.getName();
    }

    /**
     * 写入音乐媒体库
     *
     * @param context 上下文
     * @param path    音乐路径
     * @param title   音乐标题
     */
    public static boolean storeMusicInfo(Context context, String path, String title) {

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
            return storeMusicApi30(context, path, title);
        } else {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            ContentResolver resolver = context.getContentResolver();
            try {
                retriever.setDataSource(path);
                int duration = Integer.parseInt(
                        retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); //读取持续时间
                File file = new File(path);
                ContentValues values = new ContentValues();
                String extension = MimeTypeMap.getFileExtensionFromUrl(path);
                String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                values.put(MediaStore.Audio.Media.MIME_TYPE, mime);
                values.put(MediaStore.Audio.Media.DATA, path); // 文件路径
                values.put(MediaStore.Audio.Media.TITLE, title);
                values.put(MediaStore.Audio.Media.ARTIST, context.getString(R.string.sdk_name));
                values.put(MediaStore.Audio.Media.DISPLAY_NAME, file.getName());// 文件名称
                values.put(MediaStore.Audio.Media.SIZE, file.length());
                values.put(MediaStore.Audio.Media.DURATION, duration); // 播放时间
                resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            } finally {
                try {
                    retriever.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 适配Android
     */
    @RequiresApi(30)
    public static boolean storeMusicApi30(Context context, String path, String title) {

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        ContentResolver resolver = context.getContentResolver();
        try {
            retriever.setDataSource(path);
            int duration = Integer.parseInt(
                    retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); //读取持续时间
            File file = new File(path);
            ContentValues values = new ContentValues();
            String extension = MimeTypeMap.getFileExtensionFromUrl(path);
            String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            values.put(MediaStore.Audio.Media.MIME_TYPE, mime);
//            values.put(MediaStore.Audio.Media.DATA, path); // 文件路径
            values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/ve");
            values.put(MediaStore.Audio.Media.TITLE, title);
            values.put(MediaStore.Audio.Media.ARTIST, context.getString(R.string.sdk_name));
            values.put(MediaStore.Audio.Media.DISPLAY_NAME, file.getName());// 文件名称
            values.put(MediaStore.Audio.Media.SIZE, file.length());
            values.put(MediaStore.Audio.Media.DURATION, duration); // 播放时间
            Uri insertUri = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
            OutputStream out = null;
            FileInputStream fis = null;
            try {
                // First, write the actual data for our screenshot
                out = resolver.openOutputStream(insertUri);
                fis = new FileInputStream(path);
                int length = 0;
                byte[] buffer = new byte[1000];
                while ((length = fis.read(buffer, 0, buffer.length)) != -1) {
                    out.write(buffer, 0, length);
                }
                out.flush();
                // Everything went well above, publish it!
                values.clear();
                values.put(MediaStore.MediaColumns.IS_PENDING, 0);
                values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
                resolver.update(insertUri, values, null, null);
            } catch (IOException ex) {
                resolver.delete(insertUri, null, null);
                return false;
            } finally {
                if (out != null) {
                    out.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            try {
                retriever.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
